<?php

/**
 * Session类管理
 */
class Session {

    private static $lifetime = 300; //session存活时间
    private static $probability = 1; //概率

    /**
     * 更新session
     * @param array $session
     */

    public static function updateSession($session=array()) {
        global $_SGLOBAL;
        $session['dateline'] = $_SGLOBAL['timestamp'];
        $session['uid'] = $_SGLOBAL['supe_uid'] ? $_SGLOBAL['supe_uid'] : 0;
        if ($_SGLOBAL['db']->getCount('session', array('sid' => $_SGLOBAL['sid']))) {
            $setarray = array(
                'uid' => $_SGLOBAL['supe_uid'],
                'password' => $_SGLOBAL['supe_password'],
                'ip' => $_SGLOBAL['onlineip'],
                'dateline' => $_SGLOBAL['timestamp']);
            $_SGLOBAL['db']->updateTable('session', $setarray, array('sid' => $_SGLOBAL['sid']));
            $_SGLOBAL['db']->updateTable('member',array('lastupdate'=>$_SGLOBAL['timestamp']),array('uid'=>$_SGLOBAL['supe_uid']));
        } else {
            $setarray = array('sid' => $_SGLOBAL['sid'],
                'uid' => $_SGLOBAL['supe_uid'],
                'password' => $_SGLOBAL['supe_password'],
                'ip' => $_SGLOBAL['onlineip'],
                'dateline' => $_SGLOBAL['timestamp']);
            $_SGLOBAL['db']->insertTable('session', $setarray);
        }
        self::gc();
    }

    /**
     * 删除session
     */
    public static function deleteSession() {
        global $_SGLOBAL;
        $_SGLOBAL['db']->delete('session', array('sid' => $_SGLOBAL['sid']));
    }

    /**
     * session回收
     */
    public static function gc() {
        global $_SGLOBAL;
        $delete = false;
        $rand = mt_rand(1, 100);
        if (self::$probability < 50 && ($rand <= self::$probability)) {
            $delete = true;
        } elseif ($rand > self::$probability) {
            $delete = true;
        }
        if ($delete) {
            $_SGLOBAL['db']->query("DELETE FROM " . Utils::tname('session') . ' WHERE dateline<' . ($_SGLOBAL['timestamp'] - self::$lifetime));
        }
    }

}

?>
